package com.valuedaas.schoolsafety.common.annotation;

import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 处理注解 @see QuartzJobRegister
 * 
 * @author chenhua
 *
 */
@Component
public class QuartzJobRegisterBeanPostProcessor implements BeanPostProcessor {

	static final Logger LOG = LoggerFactory.getLogger(QuartzJobRegisterBeanPostProcessor.class);

	static final String DEFAULT_GROUP = "default_group";

	@Autowired
	private Scheduler scheduler;

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (bean.getClass().isAnnotationPresent(QuartzJobRegister.class)) {
			String className = bean.getClass().getName();
			LOG.info("定时任务[{}]...添加中...", beanName);
			if (bean instanceof Job) {
				try {
					// 创建一个job
					JobDetailImpl jobDetail = new JobDetailImpl();
					jobDetail.setJobClass((Class<? extends Job>) bean.getClass());
					JobKey jobKey = new JobKey(className, DEFAULT_GROUP);
					jobDetail.setKey(jobKey);
					// job的数据
					JobDataMap jobDataMap = new JobDataMap();
					jobDetail.setJobDataMap(jobDataMap);
					// trigger
					CronTriggerImpl strigger = new CronTriggerImpl();
					String cornExp = bean.getClass().getAnnotation(QuartzJobRegister.class).cron();
					TriggerKey triggerKey = new TriggerKey(className, DEFAULT_GROUP);
					strigger.setKey(triggerKey);
					strigger.setCronExpression(cornExp);
					// 开始一个定时任务
					if(scheduler.checkExists(jobKey)) {
						scheduler.rescheduleJob(triggerKey, strigger);
					}else {
						scheduler.scheduleJob(jobDetail, strigger);
					}
					LOG.info("定时任务[{}]...添加 OK!..", beanName);
				} catch (ObjectAlreadyExistsException oae) {
					LOG.warn("数据库中已经存在该任务,JobClass=" + className, oae);
				} catch (Exception pe) {
					LOG.error("添加定时任务失败,JobClass=" + className, pe);
				}
			}
		}
		return bean;
	}
}